package com.yljk.yljkproject.rnmodule;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.PermissionChecker;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import yxscan.webviewpdf.PDFActivity;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.aliyun.aliyunface.api.ZIMFacade;
import com.alsk.rn.common.ui.RNActivity;
import com.alsk.rn.kit.bridge.impl.route.KitRouterModule;
import com.baidu.mobstat.StatService;
import com.donkingliang.imageselector.utils.ImageSelector;
import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.BaseActivityEventListener;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.google.gson.Gson;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.exceptions.HyphenateException;
import com.lebanban.mp3library.MP3Recorder;
import com.luck.picture.lib.compress.Luban;
import com.previewlibrary.GPreviewBuilder;
import com.shicheng.alerts.AlertDialogManager;
import com.shicheng.alerts.callback.AlertDialogimpl;
import com.shicheng.mediaplayer.media.MediaManager;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.yilijk.base.AppBase;
import com.yilijk.base.constants.UserInfo;
import com.yilijk.base.network.config.BaseConfig;
import com.yilijk.base.network.config.BaseRouter;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.network.https.NetAttestationUtils;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.ActivityManagerUtils;
import com.yilijk.base.utils.BitmapUtils;
import com.yilijk.base.utils.ClickUtils;
import com.yilijk.base.utils.CommonUtils;
import com.yilijk.base.utils.DevicesUtils;
import com.yilijk.base.utils.LoadingUtils;
import com.yilijk.base.utils.RSAUtils;
import com.yilijk.base.utils.SharedPreferencesUtils;
import com.yljk.homedoctor.model.entity.MediaEntity;
import com.yljk.homedoctor.model.entity.VideoEntity;
import com.yljk.live.common.utils.MediaCountyManager;
import com.yljk.mcbase.network.core.NetWorkManager;
import com.yljk.mcbase.utils.utilcode.util.ActivityUtils;
import com.yljk.mcconfig.constants.MCARouter;
import com.yljk.servicemanager.bean.DoctorStatusBean;
import com.yljk.servicemanager.bean.UserInfoBean;
import com.yljk.servicemanager.constants.ConfigApi;
import com.yljk.servicemanager.constants.LocalUserInfo;
import com.yljk.servicemanager.constants.RouterApi;
import com.yljk.servicemanager.constants.UrlApi;
import com.yljk.servicemanager.db.DBOpenHelper;
import com.yljk.servicemanager.db.DataBaseUtil;
import com.yljk.servicemanager.view.preview.PreviewBuilder;
import com.yljk.yljkproject.BuildConfig;
import com.yljk.yljkproject.MyActivityManager;
import com.yljk.yljkproject.MyApplication;
import com.yljk.yljkproject.R;
import com.yljk.yljkproject.entity.CustomeEntity;
import com.yljk.yljkproject.entity.ImagesListBean;
import com.yljk.yljkproject.entity.RationalData;
import com.yljk.yljkproject.scheme.SchemeTools;
import com.yljk.yljkproject.ui.CheckActivity;
import com.yljk.yljkproject.ui.FaceActivity;
import com.yljk.yljkproject.utils.PushMessageUtil;
import com.yljk.yljkproject.utils.ReactUtils;
import com.yljk.yljkproject.utils.SearchSpUtils;
import com.yljk.yljkproject.utils.ThreeSDKInitUtils;
import com.yljk.yljkproject.utils.ThreeSDKUtils;
import com.yljk.yljkproject.utils.UmengUtils;
import com.yljk.yljkproject.utils.WXShareUtils;
import com.yljk.yljkproject.view.pickview.PickerView;
import com.yljk.yljkproject.wxapi.WXEntryActivity;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.app.Activity.RESULT_OK;
import static androidx.core.content.FileProvider.getUriForFile;
import static com.yljk.yljkproject.utils.MedicomUtils.SESSIONID;

/**
 * 原生提供给RN使用的路由方法
 * Android provide react-native router function
 */

public class RNRouterModule extends KitRouterModule {

    private static final int REQUEST_CODE = 0x00000011;
    private static final int CAMERA_CODE = 0x00000013;
    final String LOGIN_SUCCESS = "loginsuccess";
    final String ThreePartiesLogin_WeChat = "weixin";
    final String TYPE_ALBUME = "album";
    final String DATASTORAGE = "dataStorage";
    final String GETDATASTORAGE = "getDataStorage";
    final String BACKTOROOTVC = "backToRootVC";
    final String REFRESH = "refresh";
    final String LOGOUT = "logout";
    final String markMessageAsRead = "markMessageAsRead";
    private final String LOCAL_DB = "localDatabase";
    final String GET_DATASTOREDELETE = "localStorage";
    final String SAVAPICTURE = "savepicture";
    final String VIDEOANDMEDIA = "RnToNativePage";
    final String WXSHARE = "wxShare";
    final String SAVADRUGPICTURE = "saveDrugPicture";
    final String GENEREATESHAREPICTURE = "generateSharePicture";
    final String UserAgreeChecked = "userAgreeChecked";
    final String CLICK_PUSH_MESSAGE = "clickPushMessage";
    final String REDIRECT_TO_LOGIN = "redirectToLogin";
    Handler handler = new Handler();
    private String oldDir;
    String newDir;
    private HashMap<String, String> temporaryDataStorage;

    @Override
    public void dispatchScheme(@NotNull ReactContext reactContext, @NotNull String scheme, @NotNull String pageTag, @NotNull Promise promise) {
        SchemeTools.getInstance().execScheme(reactContext, scheme);
    }

    /**
     * 获取状态栏高度
     *
     * @param readableMap
     * @param promise     StatusH 状态栏高度
     *                    NavH 顶部导航栏高度
     *                    TabH 底部导航栏高度
     *                    SafeH 底部安全区域高度
     */
    @Override
    public void getEnvironmentNavigationHeight(@NotNull ReadableMap readableMap, @NotNull Promise promise) {
        int StatusH = 0; //状态栏
        int NavH = 40; //顶部导航
        int TabH = 70; //底部导航
        int SafeH = 0; //底部安全区域
        //获取状态栏高度
        int resourceId = AppBase.getApplication().getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            StatusH = AppBase.getApplication().getResources().getDimensionPixelSize(resourceId);
        }
        //创建map对象回调
        Gson gson = new Gson();
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("StatusH", StatusH);
        stringObjectHashMap.put("NavH", NavH);
        stringObjectHashMap.put("TabH", TabH);
        stringObjectHashMap.put("SafeH", SafeH);
        String s = gson.toJson(stringObjectHashMap);
        ALog.d("get", "getEnvironmentNavigationHeight: " + s);
        promise.resolve(s);

    }

    /**
     * 获取图片
     *
     * @param reactContext
     * @param readableMap
     * @param promise
     */
    private BaseActivityEventListener baseActivityEventListener;
    File outputImage;
    Uri imageUri;
    private String imagePath;

    @Override
    public void getImageAction(@NotNull ReactContext reactContext, @NotNull ReadableMap readableMap, @NotNull Promise promise) {

        //打开相册 返回本地图片路径
        //判断权限是否存在
        PackageManager pkm = reactContext.getPackageManager();
        boolean photo_permission = (PackageManager.PERMISSION_GRANTED == pkm.checkPermission("android.permission.CAMERA", reactContext.getPackageName()));
        boolean camera_permission = (PackageManager.PERMISSION_GRANTED == pkm.checkPermission("android.permission.WRITE_EXTERNAL_STORAGE", reactContext.getPackageName()));
        if (!photo_permission || !camera_permission) {
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("result", false);
                jsonObject.put("image", null);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            promise.resolve(jsonObject.toString());
            CommonUtils.getModuleCommonUtils().setRequestPermission(reactContext.getCurrentActivity(), new String[]{
                    "android.permission.CAMERA",
                    "android.permission.WRITE_EXTERNAL_STORAGE"
            }, 10001);
            return;
        }
        ALog.d("getImageAction", "getImageAction: " + readableMap.toString());
        String type = readableMap.getString("type"); //类型
        //上传头像
        if (TYPE_ALBUME.equals(type)) {
            int number = readableMap.getInt("number"); //数量
            boolean isTailoring = false;
            if (readableMap.hasKey("isTailoring")) {
                isTailoring = readableMap.getBoolean("isTailoring");
            }
            //相册
            if (isTailoring) {
                //单选并剪裁
                ImageSelector.builder()
                        .useCamera(true) // 设置是否使用拍照
                        .setCrop(true)  // 设置是否使用图片剪切功能。
                        .setCropRatio(1.0f) // 图片剪切的宽高比,默认1.0f。宽固定为手机屏幕的宽。
                        .setSingle(true)  //设置是否单选
                        .canPreview(true) //是否点击放大图片查看,，默认为true
                        .start(reactContext.getCurrentActivity(), REQUEST_CODE); // 打开相册
            } else {
                //多选(最多9张)
                ImageSelector.builder()
                        .useCamera(true) // 设置是否使用拍照
                        .setSingle(false)  //设置是否单选
                        .canPreview(true) //是否点击放大图片查看,，默认为true
                        .setMaxSelectCount(number) // 图片的最大选择数量，小于等于0时，不限数量。
                        .start(reactContext.getCurrentActivity(), REQUEST_CODE); // 打开相册
            }
        } else {//拍照
            String state = Environment.getExternalStorageState();
            if (state.equals(Environment.MEDIA_MOUNTED)) {
                String path = Environment.getExternalStorageDirectory().getPath();
                //创建拍摄图片的目录
                File file = new File(path + "/Pictures/");
                if (!file.exists()) {
                    if (!file.mkdirs()) {
                        //目录创建失败
                        ALog.e("目录创建失败");
                    }
                }
                imagePath = file.getAbsolutePath() + "/" + "h1tx" + System.currentTimeMillis() + ".jpg";
                outputImage = new File(imagePath);
//拍照后原图回存入此路径
                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
                    imageUri = Uri.fromFile(outputImage);
                } else {
                    //7.0 调用系统相机拍照不再允许使用Uri方式，应该替换为FileProvider
                    imageUri = getUriForFile(reactContext, "com.yilijk.camera.fileprovider", outputImage);
                }
                //启动相机拍照
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                if (reactContext.getCurrentActivity() != null) {
                    reactContext.getCurrentActivity().startActivityForResult(intent, CAMERA_CODE);
                }
            }
        }
        //rnactivity回调
        baseActivityEventListener = new BaseActivityEventListener() {
            @SuppressLint("CheckResult")
            @Override
            public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
                super.onActivityResult(activity, requestCode, resultCode, data);
                if (requestCode == REQUEST_CODE && data != null) {

                    ArrayList<String> images = data.getStringArrayListExtra(ImageSelector.SELECT_RESULT);
                    if (reactContext.getCurrentActivity() != null) {
                        Flowable.just(images)
                                .observeOn(Schedulers.io())
                                .map(list -> {
                                    List<File> files =
                                            Luban.with(reactContext.getCurrentActivity())
                                                    .load(list)
                                                    .setTargetDir(reactContext.getCurrentActivity().getExternalCacheDir().getAbsolutePath())
                                                    .ignoreBy(100)
                                                    .get();
                                    if (files == null) {
                                        files = new ArrayList<>();
                                    }
                                    return files;
                                })
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(files -> {
                                    String[] uris = new String[files.size()];
                                    ALog.i("imagePath", "onActivityResult: " + images.size());
                                    ALog.i("imagePath", "onActivityResult: " + uris.length);
                                    for (int i = 0; i < files.size(); i++) {
                                        ALog.d("imagePath", "onActivityResult: " + files.get(i).getPath());
                                        String path = files.get(i).getPath();
                                        Uri pa = Uri.fromFile(new File(path));//根据路径转化为uri
                                        ALog.d("imagePath", "onActivityResult: " + pa.toString());
                                        uris[i] = path;
                                    }
                                    HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                                    stringObjectHashMap.put("image", uris);
                                    stringObjectHashMap.put("result", true);
                                    String s = new Gson().toJson(stringObjectHashMap);
                                    promise.resolve(s);
                                });
                    }

                } else if (requestCode == CAMERA_CODE && resultCode == RESULT_OK) {
//                    CAMERA_CODE
                    try {
                        Bitmap bitmap = BitmapFactory.decodeStream(reactContext.getContentResolver().openInputStream(imageUri));
                        BitmapUtils.saveBitmap(bitmap, imagePath);
                        String[] strings = new String[]{imagePath};
                        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                        stringObjectHashMap.put("image", strings);
                        stringObjectHashMap.put("result", true);
                        String s = new Gson().toJson(stringObjectHashMap);
                        promise.resolve(s);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }

                } else {
                    String[] strings = new String[]{};
                    HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                    stringObjectHashMap.put("result", true);
                    stringObjectHashMap.put("image", strings);
                    String s = new Gson().toJson(stringObjectHashMap);
                    promise.resolve(s);
                }
                reactContext.removeActivityEventListener(baseActivityEventListener);
            }
        }

        ;
        reactContext.addActivityEventListener(baseActivityEventListener);
    }


    /**
     * TODO 获取定位信息
     *
     * @param reactContext
     * @param readableMap
     * @param promise
     */
    @Override
    public void getLocationInformation(@NotNull ReactContext reactContext, @NotNull ReadableMap readableMap, @NotNull Promise promise) {
        //腾讯定位信息获取
        String[] premissions = new String[]{
                "android.permission.ACCESS_FINE_LOCATION",
        };
        //判断当前版本号
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for (String s : premissions) {
                //判断权限授权执行
                if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(reactContext, s) && reactContext.getCurrentActivity() != null) {
                    ActivityCompat.requestPermissions(reactContext.getCurrentActivity(), new String[]{s}, 1);
                }
            }
        }
        TencentLocationManager tencentLocationManager = TencentLocationManager.getInstance(AppBase.getApplication());
        tencentLocationManager.requestSingleFreshLocation(null, new TencentLocationListener() {
            @Override
            public void onLocationChanged(com.tencent.map.geolocation.TencentLocation tencentLocation, int i, String s) {
                ALog.d("onLocationChanged", "onLocationChanged: " + tencentLocation.getAddress());
                ALog.d("onLocationChanged", "onLocationChanged: " + i);
                ALog.d("onLocationChanged", "onLocationChanged: " + s);
                promise.resolve(tencentLocation.getAddress());
            }

            @Override
            public void onStatusUpdate(String s, int i, String s1) {
                promise.resolve(s);
                ALog.d("onStatusUpdate", "onStatusUpdate: " + s);
                ALog.d("onStatusUpdate", "onStatusUpdate: " + i);
                ALog.d("onStatusUpdate", "onStatusUpdate: " + s1);
            }
        }, Looper.getMainLooper());

    }

    /**
     * TODO 语音长按录音 长按开始
     *
     * @param reactContext
     * @param readableMap
     * @param promise
     */
    String s;
    long startTime;
    long endTime;
    private MP3Recorder mp3Recorder;

    @Override
    public void longTouchActionWithStart(@NotNull ReactContext reactContext, @NotNull ReadableMap readableMap, @NotNull Promise promise) {
        ALog.d("长按开始录音", "longTouchCancelActionWithConfirm: ");
        //判断是否存在录音权限
        HashMap<String, Object> map = new HashMap<>();
        boolean flag = PermissionChecker.checkSelfPermission(reactContext, Manifest.permission.RECORD_AUDIO) == PermissionChecker.PERMISSION_GRANTED;
        if (flag) {
            map.put("result", true);
            promise.resolve(CommonUtils.getModuleCommonUtils().GsontoString(map));
        } else {
            CommonUtils.getModuleCommonUtils().setRequestPermission(reactContext.getCurrentActivity(), new String[]{
                    Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.CAMERA
            }, 10004);
            map.put("result", false);
            promise.resolve(CommonUtils.getModuleCommonUtils().GsontoString(map));
            return;
        }
        s = ConfigApi.voiceUrl + "/" + ReactUtils.INSTANCE.getVoiceFileName(EMClient.getInstance().getCurrentUser());

        if (!new File(ConfigApi.voiceUrl).exists()) {
            new File(ConfigApi.voiceUrl).mkdirs();
        }


        try {
            File file = new File(s);
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            mp3Recorder = new MP3Recorder(file);
            mp3Recorder.start();
            startTime = System.currentTimeMillis();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    /**
     * TODO 语音长按录音 长按取消
     *
     * @param reactContext
     * @param readableMap
     * @param promise
     */
    @Override
    public void longTouchCancelActionWithConfirm(@NotNull ReactContext reactContext, @NotNull ReadableMap readableMap, @NotNull Promise promise) {
        ALog.d("结束录音", "longTouchCancelActionWithConfirm: ");

        //AudioMp3录音

        mp3Recorder.stop();
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        endTime = System.currentTimeMillis();
//        计算当前的语音时长
        long l = endTime - startTime;
        ALog.d("long time", "getMediaRecorderTime: " + l);
        int seconds = (int) (l / 1000);
        HashMap<String, Object> voiceData = new HashMap<>();
        voiceData.put("filePath", s);
        voiceData.put("result", true);
        voiceData.put("fileTimeLength", seconds);
        promise.resolve(CommonUtils.getModuleCommonUtils().GsontoString(voiceData));
//
//


        //mediaRecoder录音

//        MediaRecorderManager.MediaRecorderStop();
//        String mediaRecorderPath = MediaRecorderManager.getMediaRecorderPath();
//        int mediaRecorderTime = MediaRecorderManager.getMediaRecorderTime();
//        HashMap<String, Object> voiceData = new HashMap<>();
//        voiceData.put("result",true);
//        voiceData.put("filePath",MediaRecorderManager.getMediaRecorderPath());
//        voiceData.put("fileTimeLength",MediaRecorderManager.getMediaRecorderTime());
//        promise.resolve(CommonUtils.getModuleCommonUtils().GsontoString(voiceData));
    }

    /**
     * TODO 打开在线客服 加载客服
     *
     * @param reactContext
     * @param readableMap
     * @param promise
     */
    @Override
    public void openCustomerService(@NotNull ReactContext reactContext, @NotNull ReadableMap readableMap, @NotNull Promise promise) {
        HashMap<String, Object> hashMap = new HashMap<>();
        HttpUtils.get(UrlApi.customer, new HttpCallBack<CustomeEntity>() {
            @Override
            public void onSuccess(CustomeEntity customeEntity, int code) {
                String s = customeEntity.getData().getUrl().replaceAll("null", "医生端");
                if ("200".equals(customeEntity.getStatus())) {
                    ARouter.getInstance().build(RouterApi.WebActivity)
                            .withString("title", "在线客服")
                            .withBoolean("ishtml", false)
                            .withString("url", s)
                            .withBoolean("isShowLoading", true).navigation();
                    hashMap.put("result", true);
                    promise.resolve(new Gson().toJson(hashMap));
                } else {
                    hashMap.put("result", false);
                    promise.resolve(new Gson().toJson(hashMap));
                }
            }

            @Override
            public void onFailure(String failureMsg, int statusCode) {

            }
        });

    }

    /**
     * TODO 打开网页WebView
     *
     * @param reactContext
     * @param readableMap
     * @param promise
     */
    @Override
    public void openNativeWeb(@NotNull ReactContext reactContext, @NotNull ReadableMap readableMap, @NotNull Promise promise) {
        ALog.d("openNativeWeb", "openNativeWeb: " + readableMap.toString());
        String s = ReactUtils.INSTANCE.delNativeMap(readableMap.toString());
        Map maps = (Map) JSON.parse(s);
        String title;
        String type;
        String url = "";
        if (maps == null) {
            return;
        }
        title = (String) maps.get("title");
        type = (String) maps.get("type");
        url = (String) maps.get("content");
        ALog.d("openNativeWeb", "openNativeWeb: " + title + url);

        if ("helpH5".equals(type)) {
            String faqId = (String) maps.get("faqId");
            String weburl = HttpUtils.getH5Url() + "/index.html?t=" + System.currentTimeMillis() + "#/faq-detail?id=" + faqId + "&tk=" + DevicesUtils.getToken();
            ALog.e(weburl);
            ARouter.getInstance().build("/WebActivity/WebActivity")
                    .withString("title", title)
                    .withString("url", weburl)
                    .withBoolean("ishtml", false)
                    .navigation();
        } else if (url.endsWith(".pdf")) {
            if (reactContext.getCurrentActivity() != null) {
                Intent intent = new Intent(reactContext.getCurrentActivity(), PDFActivity.class);
                intent.putExtra("pdfurl", url);
                intent.putExtra("title", title);
                reactContext.getCurrentActivity().startActivity(intent);
            }
        } else {
            if (url.startsWith("http")) {
                ARouter.getInstance().build("/WebActivity/WebActivity")
                        .withString("title", title)
                        .withString("url", url)
                        .withBoolean("ishtml", false)
                        .navigation();
            } else {
                ARouter.getInstance().build("/WebActivity/WebActivity")
                        .withString("title", title)
                        .withString("url", url)
                        .withBoolean("ishtml", true)
                        .navigation();
            }
        }

    }

    /**
     * TODO 拨打电话
     *
     * @param reactContext
     * @param readableMap
     * @param promise
     */
    @Override
    public void openTelprompt(@NotNull ReactContext reactContext, @NotNull ReadableMap readableMap, @NotNull Promise promise) {
        String s = readableMap.toString();
        JSONObject dataJsonObject;
        String tel = null;
        try {
            dataJsonObject = new JSONObject(s);
            String nativeMap = dataJsonObject.getString("NativeMap");
            JSONObject dataJsonObject1 = new JSONObject(nativeMap);
            tel = dataJsonObject1.getString("tel");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ArrayList<String> tels = new ArrayList<>();
        tels.add(tel);

        ReactUtils.INSTANCE.openPhoneView(reactContext, tels);
    }

    /**
     * TODO 设置状态栏颜色
     *
     * @param readableMap
     */
    @SuppressLint("LongLogTag")
    @Override
    public void setEnvironmentStatusType(@NotNull ReactContext reactContext, @NotNull ReadableMap readableMap) {
        boolean isWhite = readableMap.getBoolean("isWhite");
//        UI更新设置在主线程
        if (isWhite) {
            ALog.d("true", "setEnvironmentStatusType: ");
            //状态栏信息设置-黑色
            //获取窗口区域
            handler.post(() -> {
                if (reactContext.getCurrentActivity() != null) {
                    ReactUtils.INSTANCE.setAndroidNativeLightStatusBar(reactContext.getCurrentActivity(), isWhite);
                    ReactUtils.INSTANCE.setStatusBarColor(reactContext.getCurrentActivity(), Color.parseColor("#000000"));
                }
            });

        } else {
            handler.post(() -> {
                if (reactContext.getCurrentActivity() != null) {
                    ReactUtils.INSTANCE.setStatusBarColor(reactContext.getCurrentActivity(), Color.parseColor("#000000"));
                }
            });
            ALog.d("false", "setEnvironmentStatusType: ");
        }
    }

    /**
     * TODO 展示Scan二维码
     *
     * @param reactContext
     * @param readableMap
     * @param promise
     */
    @Override
    public void showNativeScan(@NotNull ReactContext reactContext, @NotNull ReadableMap readableMap, @NotNull Promise promise) {
        promise.resolve("true");

    }

    /**
     * TODO 展示pickView
     *
     * @param reactContext
     * @param readableMap
     * @param promise
     */
    @Override
    public void showPickView(@NotNull ReactContext reactContext, @NotNull ReadableMap readableMap, @NotNull Promise promise) {
        handler.post(() -> PickerView.getInstance(MyActivityManager.getInstance().getCurrentActivity()).getPicker(readableMap, MyActivityManager.getInstance().getCurrentActivity(), promise));
    }

    /**
     * TODO 第三方登录
     *
     * @param reactContext
     * @param readableMap
     * @param promise
     */
    @Override
    public void threePartiesLogin(@NotNull ReactContext reactContext, @NotNull ReadableMap readableMap, @NotNull Promise promise) {
        //获取登录类型
        String threePartiesLogin_type = readableMap.getString("type");
        if (threePartiesLogin_type == null) {
            ALog.e("threePartiesLogin threePartiesLogin_type == null");
            return;
        }
        if (threePartiesLogin_type.equals(ThreePartiesLogin_WeChat)) {
            //微信登录
//            WeChatUtils.INSTANCE.wechatLogin(reactContext);
            if (!CommonUtils.isWeixinAvilible(AppBase.getApplication())) {
                Toast.makeText(reactContext, "微信未安装，请先安装微信", Toast.LENGTH_SHORT).show();
            }
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "wechat_sdk_demo_test";
            MyApplication.iwxapi.sendReq(req);
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(BaseConfig.Receiver.BroadcastReceiver);
            reactContext.registerReceiver(new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    if (intent.getStringExtra("wechatCode") != null) {
                        ALog.d("微信授权成功", "onReceive: ");
                        String wechatCode = intent.getStringExtra("wechatCode");
                        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                        stringObjectHashMap.put("code", wechatCode);
                        stringObjectHashMap.put("type", "weixin");
                        stringObjectHashMap.put("result", true);
                        stringObjectHashMap.put("deviceNo", SharedPreferencesUtils.getInstance().getUment_String("deviceToken", null));
                        ALog.d("onReceive", "onReceive: " + CommonUtils.getModuleCommonUtils().GsontoString(stringObjectHashMap));
                        promise.resolve(CommonUtils.getModuleCommonUtils().GsontoString(stringObjectHashMap));
                    }
                }
            }, intentFilter);
        }
    }

    /**
     * TODO 播放语音
     *
     * @param reactContext
     * @param readableMap
     * @param promise
     */
    @Override
    public void sendMessageVoice(@NotNull ReactContext reactContext, @NotNull ReadableMap readableMap, @NotNull Promise promise) {
        RNActivity rnActivity = null;
        if (reactContext.getCurrentActivity() instanceof RNActivity) {
            rnActivity = (RNActivity) reactContext.getCurrentActivity();
        }
        if ("play".equals(readableMap.getString("voiceStatus"))) {
            if (rnActivity != null) {
                rnActivity.mediaPlay(readableMap.getString("url"));
                if (MediaManager.getMediaPlayer() != null) {
                    MediaManager.getMediaPlayer().setOnCompletionListener(mp -> {
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("result", true);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        promise.resolve(jsonObject.toString());
                    });
                }

            }
        } else if ("stop".equals(readableMap.getString("voiceStatus"))) {
            if (rnActivity != null) {
                rnActivity.mediaStop();
            }
        }
    }

    /**
     * TODO 图片预览
     *
     * @param reactContext
     * @param readableMap
     * @param promise
     */
    @Override
    public void openPhotographPreviewAction(@NotNull ReactContext reactContext, @NotNull ReadableMap readableMap, @NotNull Promise promise) {
        ArrayList<ImagesListBean> imagesListBeans = new ArrayList<>();
        if (readableMap.hasKey("index")) {
            int index = readableMap.getInt("index");
            String s = ReactUtils.INSTANCE.delNativeMap(readableMap.toString());
            if (s == null) {
                ALog.e("openPhotographPreviewAction s == null");
                return;
            }
            try {
                JSONObject jsonObject = new JSONObject(s);
                if (jsonObject.has("list")) {
                    JSONArray jsonArray = jsonObject.getJSONArray("list");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        imagesListBeans.add(new ImagesListBean((String) jsonArray.get(i)));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (reactContext.getCurrentActivity() != null && imagesListBeans.size() > 0) {
                PreviewBuilder.from(reactContext.getCurrentActivity())
                        .setData(imagesListBeans)
                        .setCurrentIndex(index)
                        .setSingleFling(true)//是否在黑屏区域点击返回
                        .setDrag(true)//是否禁用图片拖拽返回
                        .setType(PreviewBuilder.IndicatorType.Number)//指示器类型
                        .start();//启动
            }
        }

    }

    private void getAllDb(SQLiteDatabase database, String fileName) {
        Cursor cursor = null;
        try {
            cursor = database.query(fileName, null, null, null, null, null, null);
            if (cursor.moveToFirst()) {
                do {
                    int userIdIndex = cursor.getColumnIndex("_id");
                    int dataIndex = cursor.getColumnIndex("data");
                    String userId = cursor.getString(userIdIndex);
                    String data = cursor.getString(dataIndex);
                    ALog.e("oakkkdb", "query all: " + userId + " ==> " + data);
                } while (cursor.moveToNext());
            }
        } catch (Throwable throwable) {

        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
        }
    }

    /**
     * TODO 唤醒小程序
     *
     * @param reactContext
     * @param readableMap
     * @param promise
     */
    @Override
    public void openAppletsAction(@NotNull ReactContext reactContext, @NotNull ReadableMap readableMap, @NotNull Promise promise) {
        String username = readableMap.getString("username");//小程序username
        String path = readableMap.getString("path");//小程序path

        WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
        req.userName = username; // 填小程序原始id
        req.path = path;//拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"
        req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;// 可选打开 开发版，体验版和正式版
        MyApplication.iwxapi.sendReq(req);
    }

    /**
     * TODO 保存图片
     *
     * @param reactContext
     * @param readableMap
     * @param promise
     */
    @Override
    public void savepicture(@NotNull ReactContext reactContext, @NotNull ReadableMap readableMap, @NotNull Promise promise) {
        ALog.i("savapicture", "" + readableMap.toString());
    }

    /**
     * TODO 通用方法
     *
     * @param reactContext
     * @param readableMap
     * @param promise
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void toNativeGeneralAction(@NotNull ReactContext reactContext, @NotNull ReadableMap readableMap, @NotNull Promise promise) {
        ALog.i("toNativeGeneralAction", "toNativeGeneralAction: " + readableMap.toString());
        String readableMapString = ReactUtils.INSTANCE.delNativeMap(readableMap.toString());
        String dataString = null;
        JSONObject dataJson = null;
        if (readableMap.hasKey("data") && readableMapString != null) {
            try {
                dataString = new JSONObject(readableMapString).getString("data");
                ALog.d("toNativeGeneralAction", "toNativeGeneralAction: " + dataString);
                dataJson = new JSONObject(dataString);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        switch (readableMap.getString(ConfigApi.tag)) {
            case LOGIN_SUCCESS:
                toLoginSuccess(reactContext, dataJson);
                break;
            case DATASTORAGE:
                toDataStorage(dataJson);
                break;
            case GETDATASTORAGE:
                //返回给rn数据
                toGetDataStorage(promise);
                break;
            case BACKTOROOTVC:
                toHome(reactContext);
                break;
            case REFRESH:

                break;
            case LOCAL_DB: {
                toLocalDB(readableMap, promise);
                break;
            }
            case GET_DATASTOREDELETE:
                toGetOrSetData(readableMap, promise);
                break;
            case REDIRECT_TO_LOGIN:
                toRedirectToLogin(reactContext);
                break;
            case LOGOUT:
                toLogout(reactContext);
                break;
            case markMessageAsRead:
                toMessageAsRead(readableMap);
                break;
            case SAVAPICTURE:
                toSavePicture(reactContext, promise, dataJson);
                break;
            case VIDEOANDMEDIA:
                toVideoOrMedia(reactContext, readableMap, dataString);
                break;
            case WXSHARE:
                toWeChatShare(reactContext, readableMap);
                break;
            case SAVADRUGPICTURE:
                toDrugPicture(reactContext, readableMap, promise);
                break;
            case GENEREATESHAREPICTURE:
                toSaveSharePicture(reactContext, promise, dataJson);
                break;
            case "faceRecognitionMetaInfo":
                toFaceInfo(reactContext, promise);
                break;
            case "faceRecognition":
                toFaceRecognition(reactContext, promise, dataJson);
                break;
            case "Loading":
                toLoading(reactContext, readableMap);
                break;
            case "RSAEncryption":
                toRSAEncryption(readableMap, promise);
                break;
            case "stopMediaPlayer":
                MediaManager.stop();
                break;
            case "temporarySetDataStorage": {
                toSetData(dataJson);
                break;
            }
            case "temporaryGetDataStorage": {
                toGetData(promise, dataJson);
                break;
            }
            case UserAgreeChecked: {
                toUserAgreeCheck(reactContext, promise);
                break;
            }
            case "showPrivacyDialog": {
                toPrivacyDialog(promise);
                break;
            }
            case "MessageVideoPush": {
                toMessageVide0Push(readableMap);
                break;
            }
            case "BuriedPoint": {
                toBuriedPoint(reactContext, dataJson);
                break;
            }
            case "mcCheck": {
                toMCCheck(reactContext, promise, dataString);
            }
            break;
            case "getAllFunctionKey": {
                toGetAllKey(promise);
            }
            break;
            case "Dialog": {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    toDialog(reactContext);
                }
            }
            break;
            case "isHaveWeChat": {
                toHaveWeChat(promise);
            }
            break;
            case "RNSelectTheAPI": {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    toRNSelectTheAPI(reactContext);
                }
            }
            break;
            case CLICK_PUSH_MESSAGE: {
                clickPushMessage(reactContext, readableMap);
            }
            break;
            case "channelRoute": {
                JSONObject jsonObject = new JSONObject();
                try {
                    String res = dataJson.getString("res");
                    DoctorStatusBean doctorStatusBean = new Gson().fromJson(res, DoctorStatusBean.class);
                    SharedPreferencesUtils.getInstance().save(UserInfo.practiceStatus, doctorStatusBean.getData().getPracticeStatus());//本地多点状态
                    SharedPreferencesUtils.getInstance().save(UserInfo.preliminartStatus, doctorStatusBean.getData().getPreliminaryStatus());//本地初审状态
                    SharedPreferencesUtils.getInstance().save(UserInfo.departmentName, doctorStatusBean.getData().getDepartmentName());//部门名称
                    SharedPreferencesUtils.getInstance().save(UserInfo.userName, doctorStatusBean.getData().getName());//用户名称
                    SharedPreferencesUtils.getInstance().save(LocalUserInfo.hospitalName, doctorStatusBean.getData().getHospitalName());//医院名称
                    SharedPreferencesUtils.getInstance().save(UserInfo.JobtitleDesc, doctorStatusBean.getData().getTitleName());//职业
                    SharedPreferencesUtils.getInstance().save(UserInfo.imgUrl, doctorStatusBean.getData().getAvatar());//头像
                    jsonObject.put("result", true);
                    promise.resolve(jsonObject.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            break;
            case "WXReplaceHead": {
                if (!CommonUtils.isWeixinAvilible(MyApplication.getMyApplication())) {
                    Toast.makeText(reactContext, "微信未安装，请先安装微信", Toast.LENGTH_SHORT).show();
                    return;
                }
                WXEntryActivity.changeImageAvator = true;
                SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = "wechat_sdk_demo_test";
                WXEntryActivity.setCallBack(new HttpCallBack<String>() {
                    @Override
                    public void onSuccess(String s, int i) {
                        ALog.e("wechatInfo" + s);
                        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                        stringObjectHashMap.put("result", true);
                        stringObjectHashMap.put("data", s);
                        promise.resolve(CommonUtils.getModuleCommonUtils().GsontoString(stringObjectHashMap));
                    }

                    @Override
                    public void onFailure(String s, int i) {

                    }
                });
                MyApplication.iwxapi.sendReq(req);
            }
            break;
        }


    }

    private void toLocalDB(@NonNull ReadableMap readableMap, @NonNull Promise promise) {
        String fileName = "";
        String type = "";
        String dataDb = "";
        String nameKey = "";
        try {

            if (readableMap.hasKey("fileName")) {
                fileName = readableMap.getString("fileName");
                ALog.e("oakkkdb", "filename: " + fileName);
            }
            if (readableMap.hasKey("type")) {
                type = readableMap.getString("type");
                ALog.e("oakkkdb", "type: " + type);
            }
            if (readableMap.hasKey("data")) {
                dataDb = readableMap.getString("data");
                ALog.e("oakkkdb", "data: " + dataDb);
            }
            if (readableMap.hasKey("nameKey")) {
                nameKey = readableMap.getString("nameKey") + "";
                ALog.e("oakkkdb", "nameKey: " + nameKey);
            }



            switch (type) {
                case "updateData": {

                    boolean result = false;
                    if (!TextUtils.isEmpty(nameKey)) {
                        result = DataBaseUtil.getInstance().updateData(MyApplication.getMyApplication(), fileName, dataDb, nameKey);
                    } else {
                        result = DataBaseUtil.getInstance().updateData(MyApplication.getMyApplication(), fileName, dataDb);
                    }

                    HashMap<String, Object> hashMap = new HashMap<>();
                    hashMap.put("isSuccess", result);
                    promise.resolve(CommonUtils.getModuleCommonUtils().GsontoString(hashMap));

                    break;
                }
                case "setData": {

                    boolean result = false;
                    if (!TextUtils.isEmpty(nameKey)) {
                        result = DataBaseUtil.getInstance().setData(MyApplication.getMyApplication(), fileName, dataDb, nameKey);
                    } else {
                        result = DataBaseUtil.getInstance().setData(MyApplication.getMyApplication(), fileName, dataDb);
                    }

                    HashMap<String, Object> hashMap = new HashMap<>();
                    hashMap.put("isSuccess", result);
                    promise.resolve(CommonUtils.getModuleCommonUtils().GsontoString(hashMap));

                    break;
                }
                case "getData": {

                    String dataValue = "";
                    if (!TextUtils.isEmpty(nameKey)) {
                        dataValue = DataBaseUtil.getInstance().getData(MyApplication.getMyApplication(), fileName, nameKey);
                    } else {
                        dataValue = DataBaseUtil.getInstance().getData(MyApplication.getMyApplication(), fileName);
                    }
                    HashMap<String, Object> hashMap = new HashMap<>();
                    if (!TextUtils.isEmpty(dataValue)) {
                        ALog.e("oakkkdb", "datavalue: " + dataValue);
                        hashMap.put("isSuccess", true);
                        hashMap.put("data", dataValue);
                    } else {
                        hashMap.put("isSuccess", false);
                    }
                    promise.resolve(CommonUtils.getModuleCommonUtils().GsontoString(hashMap));

                    break;
                }
                case "removeData": {
                    if (!TextUtils.isEmpty(nameKey)) {
                        DataBaseUtil.getInstance().removeData(MyApplication.getMyApplication(), fileName, nameKey);
                    } else {
                        DataBaseUtil.getInstance().removeData(MyApplication.getMyApplication(), fileName);
                    }
                    HashMap<String, Object> hashMap = new HashMap<>();
                    hashMap.put("isSuccess", true);
                    promise.resolve(CommonUtils.getModuleCommonUtils().GsontoString(hashMap));

                    break;
                }

            }

        } catch (Throwable e) {
            e.printStackTrace();
            ALog.e("oakkkdb", "error: " + e.getMessage());
        } finally {
            ALog.e("oakkkdb", "finally: ");
        }
    }

    /**
     * 推送消息点击
     *
     * @param reactContext
     * @param readableMap
     */
    private void clickPushMessage(@NonNull ReactContext reactContext, @NonNull ReadableMap readableMap) {
        ReadableMap msgInfoObj = readableMap.getMap("info");
        if (msgInfoObj != null) {
            try {
                if (msgInfoObj.hasKey("scheme")) {
                    String scheme = msgInfoObj.getString("scheme");
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            boolean isLivePush = MediaCountyManager.getInstance().pageClick(scheme);
                            if (isLivePush) {
                                //直播相关的推送
                                return;
                            }
                            PushMessageUtil.getInstance().dealMessage(reactContext.getCurrentActivity(), scheme, true);
                        }
                    });
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * TODO 通用方法-TAG:RN
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void toRNSelectTheAPI(ReactContext reactContext) {
        if (!BuildConfig.OPEN_LOG) {
            return;
        }
        String[] strings = {"d1", "t1", "t2", "spare", "api"};
        AlertDialogManager.builder()
                .setContext(reactContext.getCurrentActivity())
                .setType(1)
                .setNegativeButton("取消" + "(当前环境:)" + strings[HttpUtils.getEnvironmentNo()])
                .setBottomLists(strings)
                .setBottomItemCallback(new AlertDialogimpl() {
                    @Override
                    public void Success(int i, String s) {
                        super.Success(i, s);
                        switch (i) {
                            case 0:
                                MyApplication.LocalDominNo = 0;
                                break;
                            case 1:
                                MyApplication.LocalDominNo = 1;
                                break;
                            case 2:
                                MyApplication.LocalDominNo = 2;
                                break;
                            case 3:
                                MyApplication.LocalDominNo = 3;
                                break;
                            case 4:
                                MyApplication.LocalDominNo = 4;
                                break;
                            default:

                                break;
                        }
                        ThreeSDKUtils.getInstance().IMInit(MyApplication.getMyApplication());
                        AlertDialogManager.dismiss();
                        ALog.e(MyApplication.LocalDominNo + "");
                    }
                })
                .show();
    }

    /**
     * TODO 通用方法-TAG:是否安装微信
     *
     * @param promise
     */
    private void toHaveWeChat(@NonNull Promise promise) {
        if (!CommonUtils.isWeixinAvilible(AppBase.getApplication())) {
            promise.resolve(false);
        } else {
            promise.resolve(true);
        }
    }

    /**
     * TODO 通用方法-TAG:保存图片弹窗
     *
     * @param reactContext
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void toDialog(@NonNull ReactContext reactContext) {
        AlertDialogManager.builder()
                .setContext(reactContext.getCurrentActivity())
                .setType(1)
                .setNegativeButton("取消")
                .setBottomLists(new String[]{"保存"})
                .setBottomItemCallback(new AlertDialogimpl() {
                    @Override
                    public void Success(int i, String src) {
                        super.Success(i, src);
//                        Toast.makeText(activity, i+"==="+s, Toast.LENGTH_SHORT).show();
                        if (i == 0) {
                            Bitmap bitmap;
                            if (src.startsWith("http")) {
                                bitmap = BitmapUtils.GetImageInputStream(src);
                            } else {
                                bitmap = BitmapUtils.base64ToBitmap(src.substring(src.indexOf(",") + 1));
                            }
                            if (bitmap == null) {
                                ALog.i(this.getClass().getName(), "bitmap is null");
                            } else {
//            BitmapUtils.saveBitmap(bitmap, imagePath);
                                BitmapUtils.saveImageToGallery(AppBase.getApplication(), bitmap);
                                Toast.makeText(ActivityUtils.getTopActivity(), "图片保存成功", Toast.LENGTH_SHORT).show();
                                AlertDialogManager.dismiss();
                            }
                        }
                    }
                })
                .show();
    }

    /**
     * TODO 通用方法-TAG:获取所有功能开关
     *
     * @param promise
     */
    private void toGetAllKey(@NonNull Promise promise) {
        JSONObject openJson = new JSONObject();
        try {
            openJson.put("isOpenGroup", ConfigApi.Open.isOpenGroup);
        } catch (JSONException e) {
            promise.reject(e);
            e.printStackTrace();
        }
        promise.resolve(openJson.toString());
    }

    /**
     * TODO 通用方法-TAG:美康自审
     *
     * @param reactContext
     * @param promise
     * @param dataString
     */
    private void toMCCheck(@NonNull ReactContext reactContext, @NonNull Promise promise, String dataString) {
        Intent mcCheckIntent = new Intent(reactContext.getCurrentActivity(), CheckActivity.class);
        mcCheckIntent.putExtra("sessionId", SESSIONID);

        // 需要根据 自行组织 审查参数
        ALog.d("mcPlugin", dataString);
        mcCheckIntent.putExtra("appParam", dataString);
        if (reactContext.getCurrentActivity() != null) {
            reactContext.getCurrentActivity().startActivityForResult(mcCheckIntent, REQUEST_CODE);
            ActivityEventListener activityEventListener = new ActivityEventListener() {
                @Override
                public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
                    if (resultCode == RESULT_OK) {
                        if (requestCode == REQUEST_CODE) {
                            if (data != null && data.getExtras() != null) {
                                // 如果美康内部代码或请求出错，会返回 {error: "message"}
                                ALog.d("mxPlugin", data.getExtras().getString("callBackMsg"));
                                RationalData rationalData = new Gson().fromJson(data.getExtras().getString("callBackMsg"), RationalData.class);
                                HashMap<String, Object> hashMap = new HashMap<>();
                                hashMap.put("slcode", rationalData.getSlcode());
//                                    Toast.makeText(activity, "rn cakkback mcCheck"+rationalData.getSlcode(), Toast.LENGTH_SHORT).show();
                                promise.resolve(new Gson().toJson(hashMap));
                            }
                        }
                    }
                }

                @Override
                public void onNewIntent(Intent intent) {

                }
            };
            reactContext.addActivityEventListener(activityEventListener);
        }

    }

    /**
     * TODO 通用方法-TAG:埋点
     *
     * @param reactContext
     * @param dataJson
     */
    private void toBuriedPoint(@NonNull ReactContext reactContext, JSONObject dataJson) {
        String actionID = "";
        String info = "";
        try {
            actionID = dataJson.getString("actionID");
            info = dataJson.getString("info");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JSONObject infoJSON = null;
        try {
            infoJSON = new JSONObject(info);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ClickUtils.sendEvent(actionID, reactContext.getCurrentActivity(), true, infoJSON == null ? new JSONObject() : infoJSON);
    }

    /**
     * TODO 通用方法-TAG:收到视频问诊
     *
     * @param readableMap
     */
    private void toMessageVide0Push(@NonNull ReadableMap readableMap) {
        String videoId = "";
        try {
            videoId = readableMap.getString("videoId");
        } catch (Throwable e) {
            e.printStackTrace();
        }
        ARouter.getInstance().build(MCARouter.VIDEO_CALL)
                .withString("videoId", videoId).navigation();
    }

    /**
     * TODO 通用方法-TAG:用户隐私协议
     *
     * @param promise
     */
    private void toPrivacyDialog(@NonNull Promise promise) {
        String showPrivacyDialog = SharedPreferencesUtils.getInstance().getUment_String("showPrivacyDialog", null);
        if (TextUtils.isEmpty(showPrivacyDialog)) {
            SharedPreferencesUtils.getInstance().saveUment("showPrivacyDialog", "alreadyShow");
            HashMap<String, Object> hashMap1 = new HashMap<>();
            try {
                hashMap1.put("result", true);
                ALog.e("oakkkk", "showPrivacyDialog result: " + new Gson().toJson(hashMap1));
                promise.resolve(new Gson().toJson(hashMap1));
            } catch (Throwable e) {
                e.printStackTrace();
                promise.reject(e);
            }
        }
    }

    /**
     * TODO 通用方法-TAG:用户协议同意
     *
     * @param reactContext
     * @param promise
     */
    private void toUserAgreeCheck(@NonNull ReactContext reactContext, @NonNull Promise promise) {
        MyApplication.getMyApplication().setUserAgreeChecked(true);

        String deviceNo = SharedPreferencesUtils.getInstance().getUment_String("deviceToken", null);
        if (!TextUtils.isEmpty(deviceNo) && UmengUtils.isInitialized()) {
            HashMap<String, Object> hashMap1 = new HashMap<>();
            try {
                hashMap1.put("result", "success");
                promise.resolve(new Gson().toJson(hashMap1));
            } catch (Throwable e) {
                e.printStackTrace();
                promise.reject(e);
            }
        } else {
            try {
                handler.post(() -> {

                    LoadingUtils.getLoadingUtils(reactContext.getCurrentActivity()).showLoading();

                    UmengUtils.initUmeng(AppBase.getApplication(), new UmengUtils.UmengListener() {
                        @Override
                        public void onTokenSuccess() {

                            HashMap<String, Object> hashMap = new HashMap<>();
                            try {

                                handler.post(() -> {
                                    LoadingUtils.getLoadingUtils(reactContext.getCurrentActivity()).dismissLoading();
                                });
                                hashMap.put("result", "success");
                                promise.resolve(new Gson().toJson(hashMap));
                            } catch (Throwable e) {
                                e.printStackTrace();
                                promise.reject(e);
                            }
                        }

                        @Override
                        public void onTokenFailure() {

                            HashMap<String, Object> hashMap = new HashMap<>();
                            try {

                                handler.post(() -> {
                                    LoadingUtils.getLoadingUtils(reactContext.getCurrentActivity()).dismissLoading();
                                });
                                hashMap.put("result", "failure");
                                promise.resolve(new Gson().toJson(hashMap));
                            } catch (Throwable e) {
                                e.printStackTrace();
                                promise.reject(e);
                            }
                        }
                    });
                });
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }

        if (!ThreeSDKInitUtils.getInstance().isIsInitialized()) {
            try {
                handler.post(() -> {
                    ALog.e("oakkk", "init three SDK UserAgreeChecked!");
                    ThreeSDKInitUtils.getInstance().init(AppBase.getApplication());
                });

            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }
    }

    /**
     * TODO 通用方法-TAG:临时存储- 取
     *
     * @param promise
     * @param dataJson
     */
    private void toGetData(@NonNull Promise promise, @NonNull JSONObject dataJson) {
        if (temporaryDataStorage == null) {
            temporaryDataStorage = new HashMap<>();
        }
        // 临时存储- 取
        String dataKey = "null";
        try {
            dataKey = dataJson.getString("dataKey");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String dataValue = temporaryDataStorage.get(dataKey);
        if (dataValue == null) {
            dataValue = "";
        }
        promise.resolve(dataValue);
    }

    /**
     * TODO 通用方法-TAG:临时存储- 存
     *
     * @param dataJson
     */
    private void toSetData(@NonNull JSONObject dataJson) {
        // 临时存储- 存
        if (temporaryDataStorage == null) {
            temporaryDataStorage = new HashMap<>();
        }
        String dataKey = "null";
        String dataValue = "null";
        try {
            dataKey = dataJson.getString("dataKey");
            dataValue = dataJson.getString("dataValue");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        temporaryDataStorage.put(dataKey, dataValue);
    }

    /**
     * TODO 通用方法-TAG:RSA 加密
     *
     * @param readableMap
     * @param promise
     */
    private void toRSAEncryption(@NonNull ReadableMap readableMap, @NonNull Promise promise) {
        if (ConfigApi.Open.isRSA) {
            HashMap<String, Object> hashMap = new HashMap<>();
            String encryption = readableMap.getString("encryption");
            if (encryption != null) {
                try {
                    hashMap.put("encryption", RSAUtils.encryptPublicKey(encryption));
                    promise.resolve(new Gson().toJson(hashMap));
                } catch (Exception e) {
                    e.printStackTrace();
                    promise.reject(e);
                }
            }
        }
    }

    /**
     * TODO 通用方法-TAG:rn Loading
     *
     * @param reactContext
     * @param readableMap
     */
    private void toLoading(@NonNull ReactContext reactContext, @NonNull ReadableMap readableMap) {
        try {
            if (readableMap.hasKey("isLoading") && readableMap.getBoolean("isLoading")) {
                String textStr = "";
                if (readableMap.hasKey("text") && !TextUtils.isEmpty(textStr = readableMap.getString("text"))) {
                    final String tempText = textStr;
                    handler.post(() -> LoadingUtils.getLoadingUtils(reactContext.getCurrentActivity()).showLoading(tempText));
                } else {
                    handler.post(() -> LoadingUtils.getLoadingUtils(reactContext.getCurrentActivity()).showLoading());
                }
            } else {
                handler.post(() -> LoadingUtils.getLoadingUtils(reactContext.getCurrentActivity()).dismissLoading());
            }
        } catch (Exception e) {
            ALog.d(e.getMessage(), "RN callback Loading");
        }
    }

    /**
     * TODO 通用方法-TAG:调用人脸识别
     *
     * @param reactContext
     * @param promise
     * @param dataJson
     */
    private void toFaceRecognition(@NonNull ReactContext reactContext, @NonNull Promise promise, @NonNull JSONObject dataJson) {
        String certifyId = null;
        try {
            certifyId = dataJson.getString("certifyId");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //判断是否存在相册权限
        boolean isExistCamera = PermissionChecker.checkSelfPermission(reactContext, Manifest.permission.CAMERA) == PermissionChecker.PERMISSION_GRANTED;


        if (!isExistCamera && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && reactContext.getCurrentActivity() != null) {
            reactContext.getCurrentActivity().requestPermissions(new String[]{
                    Manifest.permission.CAMERA
            }, 10001);
        }
        if (isExistCamera) {
            FaceActivity.ZimFaceCallBack zimFaceCallBack = new FaceActivity.ZimFaceCallBack() {
                @Override
                public void response(String msg) {
                    promise.resolve(msg);
                }

                @Override
                public void error(JSONException e) {
                    promise.reject(e);
                }
            };
            ARouter.getInstance().build(RouterApi.FaceActivity)
                    .withString("certifyId", certifyId)
                    .navigation();
            FaceActivity.setZimFaceCallBack(zimFaceCallBack);

        }
    }

    /**
     * TODO 通用方法-TAG:人脸识别信息
     *
     * @param reactContext
     * @param promise
     */
    private void toFaceInfo(@NonNull ReactContext reactContext, @NonNull Promise promise) {
        String metaInfos = ZIMFacade.getMetaInfos(reactContext);
        promise.resolve(metaInfos);
    }

    /**
     * TODO 通用方法-TAG:保存分享图片
     *
     * @param reactContext
     * @param promise
     * @param dataJson
     */
    private void toSaveSharePicture(@NonNull ReactContext reactContext, @NonNull Promise promise, JSONObject dataJson) {
        //判断是否存在相册权限
        boolean generateSharePictureflag = PermissionChecker.checkSelfPermission(reactContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PermissionChecker.PERMISSION_GRANTED;
        JSONObject generateSharePicturejsonObject = new JSONObject();
        if (!generateSharePictureflag) {
            try {
                generateSharePicturejsonObject.put("result", false);
                generateSharePicturejsonObject.put("msg", "检测到您还没有打开相册保存权限，请前往手机设置开启相册权限！");
                generateSharePicturejsonObject.put("filePath", "");
                CommonUtils.getModuleCommonUtils().setRequestPermission(reactContext.getCurrentActivity(), new String[]{
                        Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                }, 10005);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            promise.resolve(generateSharePicturejsonObject.toString());
            return;
        }

        String shareBg = null;
        String desc = null;
        String goodsUrl = null;
        String xcxLogo = null;
        String shareTitle = null;
        try {
            shareBg = dataJson.getString("shareBg");
            goodsUrl = dataJson.getString("goodsUrl");
            desc = dataJson.getString("desc");
            xcxLogo = dataJson.getString("xcxLogo");
            shareTitle = dataJson.getString("shareTitle");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Bitmap bitmap = BitmapUtils.GetImageInputStream(shareBg);
        Bitmap bitmap1 = BitmapUtils.GetImageInputStream(goodsUrl);
        Bitmap bitmap2 = BitmapUtils.GetImageInputStream(xcxLogo);
        //背景图片缩放
        Bitmap newBg = BitmapUtils.zoomImg(bitmap, 690, 825);
        Bitmap newDrug = BitmapUtils.zoomImg(bitmap1, 320, 320);
        //设置圆角
        newDrug = BitmapUtils.makeRoundCorner(newDrug, 25);
        Bitmap newCode = BitmapUtils.zoomImg(bitmap2, 180, 180);
        Bitmap bitmap3 = BitmapUtils.mergeBitmapDrug(newBg, newDrug, newCode, desc, shareTitle);
        newDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/com.yljk.yljkproject/files/generateSharePicture" + System.currentTimeMillis() + ".png";
        BitmapUtils.saveBitmap(bitmap3, newDir);
        try {
            generateSharePicturejsonObject.put("result", true);
            generateSharePicturejsonObject.put("msg", "保存图片成功");
            generateSharePicturejsonObject.put("filePath", newDir);
            promise.resolve(generateSharePicturejsonObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
            promise.reject(e);
        }
        //判断上次文件是否存在 存在则删除 不存在将新值赋旧值
        if (oldDir != null) {
            File file = new File(oldDir);
            if (file.exists()) {
                file.delete();
            }
        }
        if (newDir != null) {
            oldDir = newDir;
        }
    }

    /**
     * TODO 通用方法-TAG:保存药品图片
     *
     * @param reactContext
     * @param readableMap
     * @param promise
     */
    private void toDrugPicture(@NonNull ReactContext reactContext, @NonNull ReadableMap readableMap, @NonNull Promise promise) {
        //判断是否存在相册权限
        boolean saveflag = PermissionChecker.checkSelfPermission(reactContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PermissionChecker.PERMISSION_GRANTED;
        JSONObject savejsonObject = new JSONObject();
        if (!saveflag) {
            try {
                savejsonObject.put("result", false);
                savejsonObject.put("msg", "检测到您还没有打开相册保存权限，请前往手机设置开启相册权限！");
                savejsonObject.put("filePath", "");
                CommonUtils.getModuleCommonUtils().setRequestPermission(reactContext.getCurrentActivity(), new String[]{
                        Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                }, 10005);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            promise.resolve(savejsonObject.toString());
            return;
        }

        try {
            Bitmap bmp1;
            String url = readableMap.getString("imagrUrl");
            if (url != null && url.startsWith("https")) {
                ReactUtils.INSTANCE.createIgnoreVerifySSL("TLSv1.1");
                bmp1 = BitmapUtils.GetImageInputStream(url);
            } else {
                bmp1 = BitmapFactory.decodeFile(url);
            }

            //  获取当前程序路径
            String[] split = url != null ? url.split("/") : new String[0];
            if (split.length == 0) {
                ALog.e("toDrugPicture split.length is zero");
                return;
            }
            String s1 = split[split.length - 1];
            MediaStore.Images.Media.insertImage(reactContext.getContentResolver(), bmp1, s1, "暂无");
            //获得SD卡根目录路径
            File externalStorageDirectory = Environment.getExternalStorageDirectory();
            String sdpath = externalStorageDirectory.getAbsolutePath();
            ALog.i("sdpath", "toNativeGeneralAction: " + sdpath + "/Pictures/" + s1);
            savejsonObject.put("result", true);
            savejsonObject.put("msg", "保存图片成功");
            savejsonObject.put("filePath", sdpath + "/Pictures/" + s1);
            promise.resolve(savejsonObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
            try {
                savejsonObject.put("result", false);
                savejsonObject.put("msg", "保存图片失败");
                savejsonObject.put("filePath", "");
                promise.resolve(savejsonObject.toString());
            } catch (JSONException jsonException) {
                jsonException.printStackTrace();
                promise.reject(jsonException);
            }
        }
    }

    /**
     * TODO 通用方法-TAG:微信播放
     *
     * @param reactContext
     * @param readableMap
     */
    private void toWeChatShare(@NonNull ReactContext reactContext, @NonNull ReadableMap readableMap) {
        //判断微信是否安装
        if (!CommonUtils.isWeixinAvilible(AppBase.getApplication())) {
            Toast.makeText(reactContext, "微信未安装，请先安装微信", Toast.LENGTH_SHORT).show();
            return;
        }
        final String TEXT = "text";
        final String IMAGE = "image";
        final String VIDEO = "video";
        final String H5 = "h5";
        String wxShare_type = readableMap.getString("type");
        String openId = readableMap.getString("openId");
        if (wxShare_type == null) {
            return;
        }
        switch (wxShare_type) {
            case TEXT:
                String text = readableMap.getString("text");
                WXShareUtils.wxShareTxt(openId, text);
                break;
            case IMAGE:
                String imgUrl = readableMap.getString("imgUrl");
                WXShareUtils.wxShareLocalImage(openId, imgUrl);
                break;
            case VIDEO:
                String videoUrl = readableMap.getString("videoUrl");
                String videoTitle = readableMap.getString("videoTitle");
                String videoDescription = readableMap.getString("videoDescription");
                WXShareUtils.wxShareVideo(openId, videoUrl, videoTitle, videoDescription);
                break;
            case H5:
                String webUrl = readableMap.getString("webUrl");
                String webTitle = readableMap.getString("webTitle");
                String webDescription = readableMap.getString("webDescription");
                WXShareUtils.wxShareH5(openId, webUrl, webTitle, webDescription);
                break;
        }
    }

    /**
     * TODO 通用方法-TAG:患教多媒体音视频播放
     *
     * @param reactContext
     * @param readableMap
     * @param dataString
     */
    private void toVideoOrMedia(@NonNull ReactContext reactContext, @NonNull ReadableMap readableMap, String dataString) {
        //                dataJson
        String videotype = readableMap.getString("type");
        if (videotype == null) {
            ALog.e("toVideoOrMedia videotype == null");
            return;
        }
        switch (videotype) {
            case "video":
                //video
                VideoEntity videoEntity = new Gson().fromJson(dataString, VideoEntity.class);
                if (videoEntity == null) {
                    Toast.makeText(reactContext, "数据为空", Toast.LENGTH_SHORT).show();
                }
                ARouter.getInstance().build(RouterApi.VideoInfoActivity).withSerializable("videoEntity", videoEntity).navigation();
                break;
            case "audio":
                //audio
                MediaEntity mediaEntity = new Gson().fromJson(dataString, MediaEntity.class);
                if (mediaEntity == null) {
                    Toast.makeText(reactContext, "数据为空", Toast.LENGTH_SHORT).show();
                }
                ARouter.getInstance().build(RouterApi.MediaPlayerActivity).withSerializable("mediaEntity", mediaEntity).navigation();
                break;
        }
    }

    /**
     * TODO 通用方法-TAG:保存图片
     *
     * @param reactContext
     * @param promise
     * @param dataJson
     */
    private void toSavePicture(@NonNull ReactContext reactContext, @NonNull Promise promise, JSONObject dataJson) {
        //判断是否存在相册权限
        // couponsBg 优惠券背景 couponQrcode 优惠券二维码  couponName 姓名  couponJob 职业  couponRoom 科室
        boolean flag = PermissionChecker.checkSelfPermission(reactContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PermissionChecker.PERMISSION_GRANTED;
        JSONObject jsonObject = new JSONObject();
        if (!flag) {
            try {
                jsonObject.put("result", false);
                jsonObject.put("msg", "检测到您还没有打开相册保存权限，请前往手机设置开启相册权限！");
                jsonObject.put("filePath", "");
                CommonUtils.getModuleCommonUtils().setRequestPermission(reactContext.getCurrentActivity(), new String[]{
                        Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                }, 10005);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            promise.resolve(jsonObject.toString());
            return;
        }
        ReactUtils.INSTANCE.createIgnoreVerifySSL("TLSv1.1");
        try {
            Bitmap couponsBg = BitmapUtils.GetImageInputStream(dataJson.getString("imageRootPath"));
            Bitmap couponQrcode = BitmapUtils.GetImageInputStream(dataJson.getString("codeIv"));
            //  获取当前程序路径
            String picture = "活动图片" + System.currentTimeMillis() + ".jpg";
            Bitmap bitmap1 = BitmapUtils.zoomImg(couponQrcode, 330, couponQrcode.getHeight() * 330 / couponQrcode.getWidth());
            Bitmap bitmapTop = BitmapFactory.decodeResource(reactContext.getResources(), R.drawable.draw_top);
            Bitmap bitmap = BitmapUtils.mergeBitmap(couponsBg, bitmap1, bitmapTop, SharedPreferencesUtils.getInstance().getString(UserInfo.JobtitleDesc, ""),
                    SharedPreferencesUtils.getInstance().getString(UserInfo.departmentName, ""),
                    SharedPreferencesUtils.getInstance().getString(UserInfo.userName, ""));
            if (reactContext.getCurrentActivity() != null) {
                MediaStore.Images.Media.insertImage(reactContext.getCurrentActivity().getContentResolver(), bitmap, picture, "暂无");
            }
            //获得SD卡根目录路径
            File externalStorageDirectory = Environment.getExternalStorageDirectory();
            String sdpath = externalStorageDirectory.getAbsolutePath();
            ALog.i("sdpath", "toNativeGeneralAction: " + sdpath + "/Pictures/" + picture);
            jsonObject.put("result", true);
            jsonObject.put("msg", "保存图片成功");
            jsonObject.put("filePath", sdpath + "/Pictures/" + picture);
            promise.resolve(jsonObject.toString());

        } catch (JSONException e) {
            e.printStackTrace();
            try {
                jsonObject.put("result", false);
                jsonObject.put("msg", "保存图片失败");
                jsonObject.put("filePath", "");
                promise.resolve(jsonObject.toString());
            } catch (JSONException jsonException) {
                jsonException.printStackTrace();
            }

        }
    }

    /**
     * TODO 通用方法-TAG:指定会话消息未读数清零
     *
     * @param readableMap
     */
    private void toMessageAsRead(@NonNull ReadableMap readableMap) {
        String conversationId = readableMap.getString("conversationId");
        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(conversationId);
        //指定会话消息未读数清零
        conversation.markAllMessagesAsRead();
        //消息已读回执
        try {
            EMClient.getInstance().chatManager().ackConversationRead(conversationId);
        } catch (HyphenateException e) {
            e.printStackTrace();
        }
    }

    /**
     * TODO 通用方法-TAG:退出登录
     *
     * @param reactContext
     */
    private void toLogout(@NonNull ReactContext reactContext) {
        Intent loginintent = new Intent(BaseConfig.Receiver.BroadcastReceiver);
        loginintent.putExtra(ConfigApi.islogin, true);         //向广播接收器传递数据
        reactContext.sendBroadcast(loginintent);      //发送广播
        if (SharedPreferencesUtils.getInstance().removeAll()) {
            EMClient.getInstance().logout(true);
            NetAttestationUtils.getInstance().setSALT("");
            ActivityManagerUtils.finishAllActivity();
            ARouter.getInstance().build(RouterApi.CenterActivity).navigation();
        }
    }

    /**
     * 重定向到登录页面
     *
     * @param reactContext
     */
    private void toRedirectToLogin(@NonNull ReactContext reactContext) {
        Intent loginintent = new Intent(BaseConfig.Receiver.BroadcastReceiver);
        loginintent.putExtra(ConfigApi.islogin, true);         //向广播接收器传递数据
        reactContext.sendBroadcast(loginintent);      //发送广播
        if (SharedPreferencesUtils.getInstance().removeAll()) {
            EMClient.getInstance().logout(true);
//            NetAttestationUtils.getInstance().setSALT("");
            ActivityManagerUtils.finishAllActivity();
            ARouter.getInstance().build(RouterApi.CenterActivity).navigation();
        }
    }

    /**
     * TODO 通用方法-TAG:临时变量存取
     *
     * @param readableMap
     * @param promise
     */
    private void toGetOrSetData(@NonNull ReadableMap readableMap, @NonNull Promise promise) {
        StringBuilder stringBuffer = new StringBuilder();
        String fileName = null;
        String type = null;
        try {
            fileName = readableMap.getString("fileName");
            type = readableMap.getString("type");
            String s1 = ReactUtils.INSTANCE.delNativeMap(readableMap.toString());
            if (s1 != null) {
                JSONObject jsonObject = new JSONObject(s1);
                JSONArray data1 = jsonObject.getJSONArray("data");
                String history = SearchSpUtils.getInstance().getString(fileName, "");
                stringBuffer.append(history);
                for (int i = 0; i < data1.length(); i++) {
                    stringBuffer.append(data1.get(i)).append("-");
                }
            } else {
                ALog.e("toGetOrSetData s1 == null");
            }
        } catch (Exception e) {
            CommonUtils.loginfo(e.getMessage());
        }
        ALog.i("toNativeGeneralAction", "toNativeGeneralAction: " + stringBuffer);
        if (type == null) {
            ALog.e("toGetOrSetData type == null");
            return;
        }
        switch (type) {
            case "setData":
                SearchSpUtils.getInstance().save(fileName, stringBuffer.toString());
//                        SQLiteManager.getSqLiteManager().insertTableName(fileName,strings);
                break;
            case "getData":
                ArrayList<String> strings2 = new ArrayList<>();
                int count = readableMap.getInt("count");
                String string = SearchSpUtils.getInstance().getString(fileName, null);
                ALog.i("toNativeGeneralAction" + count, "toNativeGeneralAction: " + string);
                if (!TextUtils.isEmpty(string)) {
                    String[] split = string.split("-");
                    int index = Math.min(split.length, count);
                    ALog.i("toNativeGeneralAction", "toNativeGeneralAction: " + index);
                    for (int i = 0; i < index; i++) {
                        if (split[i] != null) {
                            strings2.add(split[i]);
                        }
                    }

                    ArrayList<String> finaldata = new ArrayList<>();
                    for (int i = strings2.size() - 1; i >= 0; i--) {
                        boolean flag = false;
                        for (int j = 0; j < finaldata.size(); j++) {
                            if (finaldata.get(j).equals(strings2.get(i))) {
                                flag = true;
                            }
                        }
                        if (!flag) {
                            finaldata.add(strings2.get(i));
                        }
                    }
                    HashMap<String, Object> hashMap = new HashMap<>();
                    hashMap.put("isSuccess", type);
                    hashMap.put("data", finaldata);
                    promise.resolve(CommonUtils.getModuleCommonUtils().GsontoString(hashMap));
                }
                break;
            case "removData":
                SearchSpUtils.getInstance().removekey(fileName);
                ALog.i("删除", "toNativeGeneralAction: ");
                HashMap<String, Object> hashMap1 = new HashMap<>();
                hashMap1.put("isSuccess", type);
                hashMap1.put("data", "");
                promise.resolve(CommonUtils.getModuleCommonUtils().GsontoString(hashMap1));
                break;
        }
    }


    /**
     * TODO 通用方法-TAG:去首页
     *
     * @param reactContext
     */
    private void toHome(@NonNull ReactContext reactContext) {
        if (reactContext.getCurrentActivity() != null) {
            ARouter.getInstance().build(RouterApi.MAIN_ACTIVITY).navigation();
            reactContext.getCurrentActivity().finish();
        }
    }

    /**
     * TODO 通用方法-TAG:返回给rn数据
     *
     * @param promise
     */
    private void toGetDataStorage(@NonNull Promise promise) {
        HashMap<String, Object> data = new HashMap<>();
        data.put(UserInfo.imAccount, SharedPreferencesUtils.getInstance().getString(UserInfo.imAccount, null));
        data.put(UserInfo.imPassword, SharedPreferencesUtils.getInstance().getString(UserInfo.passport, null));
        data.put(UserInfo.token, SharedPreferencesUtils.getInstance().getString(UserInfo.token, null));
        data.put(UserInfo.UserId, SharedPreferencesUtils.getInstance().getLong(UserInfo.UserId, 0));
        data.put(UserInfo.userName, SharedPreferencesUtils.getInstance().getString(UserInfo.userName, null));
        data.put(UserInfo.imgUrl, SharedPreferencesUtils.getInstance().getString(UserInfo.imgUrl, null));
        data.put(UserInfo.openId, SharedPreferencesUtils.getInstance().getString(UserInfo.openId, null));
        data.put(UserInfo.passportId, SharedPreferencesUtils.getInstance().getLong(UserInfo.passportId, 0));
        data.put(UserInfo.UserPhone, SharedPreferencesUtils.getInstance().getString(UserInfo.UserPhone, null));
        data.put(UserInfo.accountId, SharedPreferencesUtils.getInstance().getString(UserInfo.accountId, null));
        data.put("private", ConfigApi.Open.isRestServer);
        data.put("deviceId", DevicesUtils.getDeviceId());
        String s = new Gson().toJson(data);
        ALog.d("getdata", "toNativeGeneralAction: " + s);
        promise.resolve(s);
    }

    /**
     * TODO 通用方法-TAG:设置密码
     *
     * @param dataJson
     */
    private void toDataStorage(@NonNull JSONObject dataJson) {
        //设置密码
        try {
            if (dataJson.has(UserInfo.token)) {
//                    ALog.i("token", "toNativeGeneralAction: "+readableMap.getString(UserInfo.token));
                SharedPreferencesUtils.getInstance().save(UserInfo.token, dataJson.getString(UserInfo.token));
            }
            if (dataJson.has(UserInfo.openId)) {
                SharedPreferencesUtils.getInstance().save(UserInfo.openId, dataJson.getString(UserInfo.openId));
            }
            if (dataJson.has(UserInfo.mobile)) {
                SharedPreferencesUtils.getInstance().save(UserInfo.mobile, dataJson.getString(UserInfo.mobile));
            }
            if (dataJson.has(UserInfo.nickName)) {
                SharedPreferencesUtils.getInstance().save(UserInfo.nickName, dataJson.getString(UserInfo.nickName));
            }
            if (dataJson.has(UserInfo.hasPhone)) {
                SharedPreferencesUtils.getInstance().save(UserInfo.hasPhone, dataJson.getString(UserInfo.hasPhone));
            }
            if (dataJson.has(UserInfo.hasPassword)) {
                SharedPreferencesUtils.getInstance().save(UserInfo.hasPassword, dataJson.getString(UserInfo.hasPassword));
            }
            //判断是否存在mobile key 存在存储本地
            if (dataJson.has(UserInfo.account)) {
                String string = dataJson.getString(UserInfo.account);
                JSONObject jsonObject = new JSONObject(string);
                //判断是否存在openId key 存在存储本地
                if (jsonObject.has(UserInfo.accountId)) {
                    SharedPreferencesUtils.getInstance().save(UserInfo.accountId, jsonObject.getString(UserInfo.accountId));
                }
                if (jsonObject.has(UserInfo.openId)) {
                    SharedPreferencesUtils.getInstance().save(UserInfo.openId, jsonObject.getString(UserInfo.openId));
                }
                if (jsonObject.has(UserInfo.passportId)) {
                    SharedPreferencesUtils.getInstance().save(UserInfo.passportId, jsonObject.getLong(UserInfo.passportId));
                }
                if (jsonObject.has(UserInfo.imgUrl)) {
                    SharedPreferencesUtils.getInstance().save(UserInfo.imgUrl, jsonObject.getString(UserInfo.imgUrl));
                }
                if (jsonObject.has(UserInfo.mobile)) {
                    SharedPreferencesUtils.getInstance().save(UserInfo.mobile, jsonObject.getString(UserInfo.mobile));
                }
                if (jsonObject.has(UserInfo.mobileAes)) {
                    SharedPreferencesUtils.getInstance().save(UserInfo.mobileAes, jsonObject.getString(UserInfo.mobileAes));
                }
                if (jsonObject.has(UserInfo.nickName)) {
                    SharedPreferencesUtils.getInstance().save(UserInfo.nickName, jsonObject.getString(UserInfo.nickName));
                }
                if (jsonObject.has(UserInfo.imAccount)) {
                    SharedPreferencesUtils.getInstance().save(UserInfo.imAccount, jsonObject.getString(UserInfo.imAccount));
                }
                if (jsonObject.has(UserInfo.imPassword)) {
                    SharedPreferencesUtils.getInstance().save(UserInfo.imPassword, jsonObject.getString(UserInfo.imPassword));
                }


            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * TODO 通用方法-TAG:登录成功
     *
     * @param reactContext
     * @param dataJson
     */
    private void toLoginSuccess(@NonNull ReactContext reactContext, @NonNull JSONObject dataJson) {
        //判断是否存在token key 存在存储本地
        UserInfoBean userInfoBean = new Gson().fromJson(dataJson.toString(), UserInfoBean.class);
        SharedPreferencesUtils.getInstance().save(UserInfo.token, userInfoBean.getToken());
        SharedPreferencesUtils.getInstance().save(UserInfo.hasPassword, userInfoBean.getHasPassword());
        SharedPreferencesUtils.getInstance().save(UserInfo.hasPhone, userInfoBean.getHasPhone());
        SharedPreferencesUtils.getInstance().save(UserInfo.passport, userInfoBean.getPassport());
        SharedPreferencesUtils.getInstance().save(LocalUserInfo.isNew, userInfoBean.getIsNew());
        UserInfoBean.AccountBean account = userInfoBean.getAccount();
        SharedPreferencesUtils.getInstance().save(UserInfo.nickName, account.getNickName());
        SharedPreferencesUtils.getInstance().save(UserInfo.passportId, account.getPassportId());
        SharedPreferencesUtils.getInstance().save(UserInfo.mobile, account.getMobile());
        SharedPreferencesUtils.getInstance().save(UserInfo.imAccount, account.getImAccount());
        SharedPreferencesUtils.getInstance().save(LocalUserInfo.imgUrl, account.getImgUrl());
        SharedPreferencesUtils.getInstance().save(UserInfo.openId, account.getOpenId());
        SharedPreferencesUtils.getInstance().save(UserInfo.mobileAes, account.getMobileAes());
        SharedPreferencesUtils.getInstance().save(UserInfo.accountId, account.getId() + "");
        SharedPreferencesUtils.getInstance().save(UserInfo.imPassword, account.getImPassword());
        MediaCountyManager.getInstance().appLogin();
        StatService.setAuthorizedState(AppBase.getApplication(), true);
        ARouter.getInstance().build(RouterApi.CenterActivity).navigation();
        handler.post(new Runnable() {
            @Override
            public void run() {
                UmengUtils.addUmengAddAlias(AppBase.getApplication());
            }
        });
        Intent intent = new Intent(BaseConfig.Receiver.BroadcastReceiver);
//                intent.putExtra(UserInfo.refreshAll,true);         //向广播接收器传递数据
        intent.putExtra(ConfigApi.refreshMain, true);         //向广播接收器传递数据
        intent.putExtra(ConfigApi.refreshMy, true);         //向广播接收器传递数据
        intent.putExtra(ConfigApi.refreshHome, true);         //向广播接收器传递数据
        reactContext.sendBroadcast(intent);      //发送广播
//                Intent intent1 = new Intent();
//                intent.setClass(reactContext.getCurrentActivity(), MainActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  //注意本行的FLAG设置
//                reactContext.startActivity(intent1);
    }


}
